//
//  ST_ChatModuleViewController.swift
//  btvideo
//
//  Created by mac on 2020/1/16.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import NIMSDK
import SwiftyUserDefaults
import RxSwift
import RxCocoa

//1_消息_配对
class ST_ChatModuleViewController: UIViewController {

    static let shared = ST_ChatModuleViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = Color.white
        
        
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight + 54, left: 0, bottom: 0, right: 0))
        }
        
        scrollView.addSubview(root_view)
        
        let h = ScreenHeight - statusBarHeight - 54
        
        root_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.width.equalTo(ScreenWidth*3)
            make.height.equalTo(h)
        }
        
        self.addChild(close_friends_controller)
        self.addChild(msg_controller)
        self.addChild(recent_calls_controller)
        
        root_view.addSubview(close_friends_controller.view)
        root_view.addSubview(msg_controller.view)
        root_view.addSubview(recent_calls_controller.view)
        
        
        close_friends_controller.view.snp.makeConstraints { (make) in
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(h)
            make.top.bottom.left.equalToSuperview()
        }
        
        msg_controller.view.snp.makeConstraints { (make) in
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(h)
            make.top.bottom.centerX.equalToSuperview()
        }
        
        recent_calls_controller.view.snp.makeConstraints { (make) in
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(h)
            make.top.bottom.right.equalToSuperview()
        }
        
        
        self.view.addSubview(close_friends_btn)
        self.view.addSubview(msg_btn)
        self.view.addSubview(recent_calls_btn)
        
        let relativeOffset = 10/375*ScreenWidth
        
        msg_btn.snp.makeConstraints { (make) in
            make.width.equalTo(76)
            make.height.equalTo(38)
            make.top.equalToSuperview().offset(statusBarHeight+3)
            make.centerX.equalToSuperview()
        }
        
        close_friends_btn.snp.makeConstraints { (make) in
            make.width.equalTo(76)
            make.height.equalTo(38)
            make.top.equalToSuperview().offset(statusBarHeight+3)
            make.right.equalTo(msg_btn.snp.left).offset(-relativeOffset)
        }
        
        
        recent_calls_btn.snp.makeConstraints { (make) in
            make.width.equalTo(80)
            make.height.equalTo(38)
            make.top.equalToSuperview().offset(statusBarHeight+3)
            make.left.equalTo(msg_btn.snp.right).offset(relativeOffset)
        }
        
        
        self.view.addSubview(unread_message_number_label)
        unread_message_number_label.snp.makeConstraints { (make) in
            make.centerX.equalTo(msg_btn.snp.right).offset(-11)
            make.top.equalTo(msg_btn).offset(5)
            make.height.equalTo(18)
            make.width.equalTo(18)
        }
        
        
        view.addSubview(close_friends_level_btn)
        close_friends_level_btn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(7)
            make.width.height.equalTo(44)
            make.centerY.equalTo(close_friends_btn)
        }
        
        
        
        view.addSubview(received_history_btn)
        received_history_btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(44)
            make.centerY.equalTo(close_friends_btn)
        }
        
        view.addSubview(clear_recent_sessions_btn)
        clear_recent_sessions_btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(44)
            make.centerY.equalTo(close_friends_btn)
        }
        
        
        main_thread_execute(afterDelay: 1) {
            self.scrollView.contentOffset = CGPoint.init(x: ScreenWidth, y: 0)
        }
        
        ST_ConversationAdapter.shared.unread_number_observer.distinctUntilChanged().subscribe(onNext: {[weak self] n in
            
            self?.refresh_unread_number(unreadNimCount: n)
            
        }).disposed(by: disposeBag)
        
    }
    
    
//    MARK:-properties
    
    var disposeBag = DisposeBag()
    
    fileprivate lazy var scrollView:UIScrollView = {
       let control = UIScrollView()
        control.backgroundColor = Color.white
        control.isPagingEnabled = true
//        control.isScrollEnabled = false
        control.delegate = self
       return control
    }()
    
    
    fileprivate lazy var root_view:UIView = {
        let control = UIView()
        control.backgroundColor = Color.white
        return control
    }()
    
    fileprivate lazy var close_friends_controller = ST_CloseFriendsViewController()
    
    fileprivate lazy var msg_controller = ST_BTMessageController()
    
    
    lazy var recent_calls_controller = ST_RecentCallsViewController()
    
    fileprivate lazy var btn_selected_image:UIImage = {
       let img = UIImage.init(color: UIColor.init(hexString: "#FEC207")!, size: CGSize.init(width: 1, height: 1))
       return img
   }()
       
   fileprivate lazy var btn_normal_image:UIImage = {
       let img = UIImage.init(color: UIColor.white, size: CGSize.init(width: 1, height: 1))
       return img
   }()
    
    fileprivate lazy var close_friends_level_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        control.setImage(ST_ImageUtils.imageName("chat_module_explain_icon"), for: .normal)
        control.setTitleColor(UIColor.init(hex: 0x999999)!, for: UIControl.State.normal)
        control.alpha = 0
        control.addTarget(self, action: #selector(push_level_controller), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate var baseTag = 1023

    fileprivate lazy var last_btn = msg_btn
    
    fileprivate lazy var close_friends_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setBackgroundImage(btn_selected_image, for: UIControl.State.selected)
        control.setBackgroundImage(btn_normal_image, for: UIControl.State.normal)
        control.cornerRadius = 19
        control.setTitleForAllStates("密友")
        control.setTitleColorForAllStates(UIColor.init(hexString: "#333333")!)
        control.tag = self.baseTag
        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        control.setTitleColor(UIColor.white, for: UIControl.State.selected)
        control.addTarget(self, action: #selector(click_switch_controller_handle(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var msg_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setBackgroundImage(btn_selected_image, for: UIControl.State.selected)
        control.setBackgroundImage(btn_normal_image, for: UIControl.State.normal)
        control.isSelected = true
        control.cornerRadius = 19
        control.setTitleForAllStates("聊天")
        control.setTitleColorForAllStates(UIColor.init(hexString: "#333333")!)
        control.tag = self.baseTag + 1
        control.setTitleColor(UIColor.white, for: UIControl.State.selected)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        control.addTarget(self, action: #selector(click_switch_controller_handle(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var recent_calls_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setBackgroundImage(btn_selected_image, for: UIControl.State.selected)
        control.setBackgroundImage(btn_normal_image, for: UIControl.State.normal)
        control.cornerRadius = 19
        control.setTitleForAllStates("通话")
        control.tag = self.baseTag + 2
        control.setTitleColorForAllStates(UIColor.init(hexString: "#333333")!)
        control.setTitleColor(UIColor.white, for: UIControl.State.selected)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        control.addTarget(self, action: #selector(click_switch_controller_handle(sender:)), for: UIControl.Event.touchUpInside)
        
        control.addSubview(redPoint)
        redPoint.snp.makeConstraints { (make) in
            make.height.width.equalTo(red_point_width)
            make.top.equalToSuperview().offset(3)
            make.right.equalToSuperview().offset(-19/2)
        }
        
        return control
    }()
    
    
    fileprivate lazy var received_history_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("收礼记录")
        control.setTitleColorForAllStates(#colorLiteral(red: 0.6745098039, green: 0.7058823529, blue: 0.7529411765, alpha: 1))
        control.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        control.alpha = 0
        control.addTarget(self, action: #selector(push_received_history_controller), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    
    fileprivate lazy var clear_recent_sessions_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.alpha = 1
        control.setImage(ST_ImageUtils.imageName("clear_recent_sessions_icon"), for: .normal)
        control.addTarget(self, action: #selector(clear_recent_sessions_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate let red_point_width:CGFloat = 10
    
    fileprivate lazy var redPoint:UIView = {
        let v = UIView()
        v.alpha = 1
        v.backgroundColor = UIColor.red
        v.cornerRadius = red_point_width/2.0
        return v
    }()
 
    fileprivate lazy var unread_message_number_label:UILabel = {
        let control = UILabel()
        control.cornerRadius = 18/2.0
        control.backgroundColor = UIColor.init(hexString: "#EB3C3C")!
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        control.textColor = UIColor.white
        control.textAlignment = .center
        control.isHidden = true
        control.alpha = 0
        return control
    }()
  
    
    
    private(set) var curr_filter = ST_PinterestHomeFilterModel()
    
    fileprivate var already_display_unread_feature = false
    
//    var unreadMatchArray = Set<String>()
    
}


//MARK: - Event
extension ST_ChatModuleViewController{
    

    fileprivate func refresh_unread_number(unreadNimCount:Int){
        
        if unreadNimCount > 99{
            self.unread_message_number_label.text = "99+"
            self.unread_message_number_label.snp.updateConstraints { (make) in
                make.width.equalTo(30)
            }
            self.unread_message_number_label.isHidden = false
        }else if unreadNimCount > 0 {
            self.unread_message_number_label.text = unreadNimCount.string
            self.unread_message_number_label.snp.updateConstraints { (make) in
                make.width.equalTo(unreadNimCount > 9 ? 24 : 18)
            }
            self.unread_message_number_label.isHidden = false
        }else{
            self.unread_message_number_label.isHidden = true
        }
    }
    
    func current_display_tab_index()->Int{
        
        return last_btn.tag - self.baseTag
    }
    
    @objc fileprivate func clear_recent_sessions_handle(){
        
        self.msg_controller.clear_recent_sessions_handle()
    }
    
    @objc fileprivate func push_received_history_controller(){
        
        navigationController?.pushViewController(ST_GiftHistoryViewController())
        
    }
    
    @objc fileprivate func push_level_controller(){
        
        navigationController?.pushViewController(ST_SweetRankViewController())
        
    }
   
    @objc func click_switch_controller_handle(sender:UIButton){
        
        if sender.isSelected{
            return
        }
        
        last_btn.isSelected = false
        
        sender.isSelected = true
        
        last_btn = sender
        
        let offsetX = (sender.tag - self.baseTag).cgFloat * ScreenWidth
        
        scrollView.setContentOffset(CGPoint.init(x: offsetX, y: 0), animated: true)
        
        unread_message_number_label.alpha = sender == msg_btn ? 0 : 1
        
        if sender == recent_calls_btn {
            
            redPoint.alpha = 0
        }
        
        received_history_btn.alpha = sender == close_friends_btn ? 1 : 0
        
        close_friends_level_btn.alpha = sender == close_friends_btn ? 1 : 0
        
        clear_recent_sessions_btn.alpha = sender == msg_btn ? 1 : 0
        
        ST_BTLaunchController.shared.setting_unread_msg_count()
    }
    
    /**
     又展示到 当前 tab
     */
    func disply_current_tab_again(){
        
        if close_friends_btn.isSelected {
            
            ST_BTLaunchController.shared.setting_unread_msg_count()
            
        }
        
    }
    
    
    
    
}

extension ST_ChatModuleViewController:UIScrollViewDelegate{
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        let  page = (scrollView.contentOffset.x + (0.5 * ScreenWidth)) / ScreenWidth
        
        if  page.int == 0{
            click_switch_controller_handle(sender: self.close_friends_btn)
        }else if  page.int == 1{
            click_switch_controller_handle(sender: self.msg_btn)
        }else {
            click_switch_controller_handle(sender: self.recent_calls_btn)
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        
        
    }
    
}



//MARK: - Match Unread Count
extension ST_ChatModuleViewController{
    
    /**
     解除匹配 更新角标
     */
    func remove_match_unread_handle(accid:String){
        
    }
    
    
    func receive_match_handle(accid:String) {
       
        ST_BTLaunchController.shared.setting_unread_msg_count()
        
    }
    
    
    
}


